import 'package:flutter/material.dart';
import 'package:flutter_app/constant/const_string.dart';
import 'package:flutter_app/pages/white_board/scale_layer_logic.dart';
import 'package:flutter_app/pages/white_board/white_board_vm.dart';
import 'package:flutter_app/utils/paint_util.dart';

extension GestureDetectorLogic on WhiteBoardVM {
  void onScaleStart(ScaleStartDetails details) {
    if (details.pointerCount > 2) {
      lastScaleUpdateDetails = null;
    }
  }

  void onScaleUpdate(ScaleUpdateDetails details) {
    if (details.pointerCount >= 2) {
      _executeTranslating(details);
      _executeScaling(details);
    }
  }

  void onScaleEnd(ScaleEndDetails details) {
    if (details.pointerCount < 2) {
      lastScaleUpdateDetails = null;
    }
  }

  // 执行缩放
  void _executeScaling(ScaleUpdateDetails details) {
    if (lastScaleUpdateDetails == null) {
      lastScaleUpdateDetails = details;
      return;
    }

    double scaleIncrement = details.scale - lastScaleUpdateDetails!.scale;
    aroundCenterScale(
      type: scaleIncrement > 0
          ? ScaleLayerWidgetType.zoomIn
          : ScaleLayerWidgetType.zoomOut,
      center: details.localFocalPoint,
      stepScale: scaleIncrement.abs(),
    );

    // 缩放过程中实时更新上一次缩放的数据
    lastScaleUpdateDetails = details;
  }

  // 执行平移
  void _executeTranslating(ScaleUpdateDetails details) {
    curCanvasOffset += details.focalPointDelta;
  }
}

extension ListenerLogic on WhiteBoardVM {
  void onPointerDown(PointerDownEvent event) {
    final index = graphicsList.indexWhere(
      (element) {
        return PaintUtil.isPointInPolygon(event.localPosition, element.points);
      },
    );
    for (var element in graphicsList) {
      element.isSelected = false;
    }
    if (index != -1) {
      // 选中
      graphicsList[index].isSelected = true;
    }
    update(
      [ConstString.graphicsLayerWidgetId],
    );
  }
}
